<template>
  <div class="createPost-container">
    <el-form
      ref="postForm"
      :model="postForm"
      :rules="rules"
      class="form-container"
    >
      <div class="createPost-main-container">
        <el-button
          v-loading="loading"
          style="margin-left: 10px"
          type="success"
          @click="submitForm"
        >
          Publish
        </el-button>
        <el-button v-loading="loading" type="warning" @click="draftForm">
          Draft
        </el-button>
        <PlatformDropdown
          v-model="postForm.eventType"
          :eflag="eflag"
          :platforms-option-list="platformsOptionList"
        />
        <el-row>
          <el-col :span="24">
            <el-form-item style="margin-bottom: 40px" prop="title">
              <MDinput
                v-model="postForm.eventName"
                :maxlength="100"
                name="name"
                required
              >
                Title
              </MDinput>
            </el-form-item>

            <div class="postInfo-container">
              <el-row>
                <el-col :span="8">
                  <el-form-item
                    label-width="60px"
                    label="Author:"
                    class="postInfo-container-item"
                    prop="author"
                  >
                    <el-select
                      v-model="postForm.author"
                      :remote-method="getRemoteUserList"
                      filterable
                      default-first-option
                      remote
                      placeholder="Search user"
                    >
                      <el-option
                        v-for="(item, index) in userListOptions"
                        :key="item + index"
                        :label="item"
                        :value="item"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="10">
                  <el-form-item
                    label-width="120px"
                    label="Publish Time:"
                    class="postInfo-container-item"
                  >
                    <el-date-picker
                      v-model="createDate"
                      type="datetime"
                      format="yyyy-MM-dd HH:mm:ss"
                      placeholder="Select date and time"
                    />
                  </el-form-item>
                </el-col>

                <el-col :span="6">
                  <el-form-item
                    label-width="90px"
                    label="Importance:"
                    class="postInfo-container-item"
                    prop="importance"
                  >
                    <el-rate
                      v-model="postForm.importance"
                      :max="3"
                      :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                      :low-threshold="1"
                      :high-threshold="3"
                      style="display: inline-block"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>

        <el-form-item
          style="margin-bottom: 40px"
          label-width="70px"
          label="Summary:"
          prop="contentShort"
        >
          <el-input
            v-model="postForm.contentShort"
            :rows="1"
            type="textarea"
            class="article-textarea"
            autosize
            placeholder="Please enter the content"
          />
          <!-- <span v-show="contentShortLength" class="word-counter">{{ contentShortLength }}words</span> -->
        </el-form-item>

        <el-form-item prop="content" style="margin-bottom: 30px">
          <Tinymce ref="editor" v-model="postForm.eventContent" :height="400" />
        </el-form-item>

        <!-- <el-form-item prop="image_uri" style="margin-bottom: 30px;">
          <Upload v-model="postForm.image_uri" />
        </el-form-item> -->
      </div>
    </el-form>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce';
import Upload from '@/components/Upload/SingleImage3';
import MDinput from '@/components/MDinput';
import Sticky from '@/components/Sticky'; // 粘性header组件
import { validURL } from '@/utils/validate';
import {
  CommentDropdown,
  PlatformDropdown,
  SourceUrlDropdown
} from './Dropdown';

const defaultForm = {
  state: 'draft',
  eventName: '', // 文章题目
  eventContent: '', // 文章内容
  contentShort: '', // 文章摘要
  source_uri: '', // 文章外链
  // image_uri: "", // 文章图片
  createDate: undefined, // 前台展示时间
  eventId: undefined,
  eventType: '0',
  // comment_disabled: false,
  importance: 0
};

export default {
  name: 'ArticleDetail',
  components: {
    Tinymce,
    MDinput,
    Upload,
    Sticky,
    CommentDropdown,
    PlatformDropdown,
    SourceUrlDropdown
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: rule.field + '为必传项',
          type: 'error'
        });
        callback(new Error(rule.field + '为必传项'));
      } else {
        callback();
      }
    };
    const validateSourceUri = (rule, value, callback) => {
      if (value) {
        if (validURL(value)) {
          callback();
        } else {
          this.$message({
            message: '外链url填写不正确',
            type: 'error'
          });
          callback(new Error('外链url填写不正确'));
        }
      } else {
        callback();
      }
    };
    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      userListOptions: [],
      rules: {
        // image_uri: [{ validator: validateRequire }],
        noticeType: [{ required: true, message: '请选择事件类型' }],
        author: [{ required: true, message: '请选择作者' }],
        importance: [{ required: true, message: '请选择重要程度' }],
        // date: [{type:"date", required: true, message: "请选择日期" ,trigger: 'change'}],
        contentShort: [
          { required: true, message: '请输入文章摘要', trigger: 'blur' }
        ]
        // source_uri: [{ validator: validateSourceUri, trigger: "blur" }]
      },
      platformsOptionList: [
        { key: '1', name: '讲座' },
        { key: '2', name: '展览' },
        { key: '3', name: '活动' }
      ],
      eflag: 'events',
      tempRoute: {}
    };
  },
  computed: {
    contentShortLength() {
      // return this.postForm.content_short.length;
    },
    createDate: {
      // set and get is useful when the data
      // returned by the back end api is different from the front end
      // back end return => "2013-06-25 06:59:25"
      // front end need timestamp => 1372114765000
      get() {
        // var d = new Date(this.postForm.createDate);
        // var str=d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
        return +new Date(this.postForm.createDate);
      },
      set(val) {
        var d = val;
        var str =
          d.getFullYear() +
          '-' +
          (d.getMonth() + 1) +
          '-' +
          d.getDate() +
          ' ' +
          d.getHours() +
          ':' +
          d.getMinutes() +
          ':' +
          d.getSeconds();
        this.postForm.createDate = str;
      }
    }
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.query.eventId;
      this.fetchData(id);
    }
    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route);
  },
  activiti() {
    this.init();
  },
  distoryed() { },
  methods: {
    fetchData(id) {
      var queryObj = {
        eventId: id
      };
      this.$get('study/lEvent', {
        ...queryObj
      })
        .then(response => {
          this.postForm = response.data.resultBody;

          // just for test
          this.postForm.eventName += `Article Id:${this.postForm.eventId}`;
          this.postForm.contentShort += `Article Id:${this.postForm.eventId}`;

          // set tagsview title
          // this.setTagsViewTitle();

          // set page title
          // this.setPageTitle();
        })
        .catch(err => {
          console.log(err);
        });
    },
    setTagsViewTitle() {
      const title = 'Edit Article';
      const route = Object.assign({}, this.tempRoute, {
        title: `${title}-${this.postForm.eventId}`
      });
      this.$store.dispatch('tagsView/updateVisitedView', route);
    },
    setPageTitle() {
      const title = 'Edit Article';
      document.title = `${title} - ${this.postForm.eventId}`;
    },
    submitForm() {
      debugger;
      if (
        this.postForm.eventContent.length === 0 ||
        this.postForm.eventName.length === 0
      ) {
        this.$message({
          message: '请填写必要的标题和内容',
          type: 'warning'
        });
        return;
      }
      this.postForm.state = 'published';
      console.log(this.postForm);
      this.$refs.postForm.validate(valid => {
        debugger;
        if (valid) {
          this.loading = true;
          if (!this.postForm.eventId) {
            this.$post('study/lEvent', { ...this.postForm }).then(res => {
              this.loading = false;
              this.$notify({
                title: '成功',
                message: '发布文章成功',
                type: 'success',
                duration: 2000
              });
            });
          } else {
            this.$put('study/lEvent', { ...this.postForm }).then(res => {
              this.loading = false;
              this.$notify({
                title: '成功',
                message: '发布文章成功',
                type: 'success',
                duration: 2000
              });
            });
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    draftForm() {
      if (
        this.postForm.eventContent.length === 0 ||
        this.postForm.eventName.length === 0
      ) {
        this.$message({
          message: '请填写必要的标题和内容',
          type: 'warning'
        });
        return;
      }
      this.postForm.state = 'draft';
      console.log(this.postForm);
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true;
          if (!this.postForm.eventId) {
            this.$post('study/lEvent', { ...this.postForm }).then(res => {
              this.loading = false;
              this.$notify({
                title: '成功',
                message: '发布文章成功',
                type: 'success',
                duration: 2000
              });
            });
          } else {
            this.$put('study/lEvent', { ...this.postForm }).then(res => {
              this.loading = false;
              this.$notify({
                title: '成功',
                message: '发布文章成功',
                type: 'success',
                duration: 2000
              });
            });
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    getRemoteUserList(query) {
      this.$get('system/user').then(r => {
        const data = r.data.resultBody;
        this.userListOptions = data.records.map(v => v.username);
      });
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea /deep/ {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
